import '@nutui/nutui-react/dist/style.css'
import React, { useState, useEffect } from 'react'
import { Input } from '@nutui/nutui-react'
import './locationa.css'
import axios from 'axios'
import { SearchOutline, SetOutline } from 'antd-mobile-icons'
import { Map, Marker } from 'react-amap';
import Geolocation from 'react-amap-plugin-geolocation';
import {useNavigate} from 'react-router-dom'
import { Card } from 'antd-mobile'
// import AMapLoader from '@amap/amap-jsapi-loader';
export default function Location() {
  const navigate = useNavigate()
  const pluginProps = {
    enableHighAccuracy: true,
    timeout: 10000,
    showButton: true,
    zoomToAccuracy: true,
    panToLocation: true,//定位成功后是否将定位到的位置作为地图中心点
    showMarker: true,
  }
  const [longitude, setlongitude] = useState(0) //经度
  const [latitude, setlatitude] = useState(0)//纬度
  const [position, setPosition] = useState(null);
  const [nearbyLocations, setNearbyLocations] = useState([]);
  const [dict, setdict] = useState(null)//地址
  const [address, setaddress] = useState(null)// 地址
  const [addressList, setaddressList] = useState([])// 地址列表
  const onSearchAddress = (address) => {
    fetch(`https://restapi.amap.com/v3/geocode/geo?key=${"f2359fd70aa9c76fe51adfd704c66cd0"}&address=${address}`)
      .then(res => {
        if (!res.ok) {
          throw new Error(res.statusText); // 如果响应不正常，抛出错误
        }
        return res.json();
      })
      .then(data => {
        if (data.geocodes && data.geocodes.length > 0) {
          const location = data.geocodes[0].location.split(',');
          const lng = parseFloat(location[0]);  //经度
          const lat = parseFloat(location[1]);  //纬度
          setlongitude(lng);
          setlatitude(lat);
          setdict(data)
          // console.log(data.geocodes);
          console.log(data);
          setaddressList(data.geocodes)
          // console.log(lng, lat);
        }
      })
      .catch(err => {
        console.error('Error:', err);
      })
  };

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setPosition(position);
          fetchNearbyLocations(position.coords); // 直接传递coords
        },
        (error) => {
          console.error("Error getting current position:", error);
        }
      );
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  }, [])
  const fetchNearbyLocations = (coords) => {
    axios.get(
      `https://restapi.amap.com/v3/place/text?keywords=市&types=&city=&children=&offset=20&page=1&extensions=&output=json&location=${coords.longitude},${coords.latitude}&radius=99999999999999&key=${"f2359fd70aa9c76fe51adfd704c66cd0"}`
    ).then(response => {
      setNearbyLocations(response.data.pois);
      setaddressList(response.data.pois)
    }).catch(error => {
      console.error("Error fetching nearby locations:", error);
    });
  };
  const goshow = (item) => {
    if(item.city){
      let city = {city:item.city,location:item.location};
      localStorage.setItem("city",JSON.stringify(city));
    }else{
      let city = {city:item.cityname,location:item.location};
      localStorage.setItem("city",JSON.stringify(city));
    }
    navigate('/app/show')
  }
  return (
    <div className='location'>
      <div className='map'>
        <Map amapkey={"f2359fd70aa9c76fe51adfd704c66cd0"} zoom={21} plugins={['ToolBar']} center={[longitude, latitude]}>
          {longitude !== null && latitude !== null && (
            <Marker position={{ longitude: longitude, latitude: latitude }} />
          )}
          <Geolocation {...pluginProps} />
        </Map>
        <div className='close'>
          <img src='https://cdn7.axureshop.com/demo2024/2293659/images/18-%E4%BD%8D%E7%BD%AE%E6%8E%88%E6%9D%83/close_u673.svg'></img>
        </div>
        <Card>
          <div className='card_top'></div>
        </Card>
      </div>
      <div className='address'>
        <div className='address_top'>
          <SearchOutline />
          <Input placeholder="搜索地点" style={{ border: '0.0625rem solid #ccc' }} onChange={(e) => {
            setaddress(e)
          }}
            onKeyDown={(e) => {

              if (e.keyCode == 13) {
                onSearchAddress(address)
              }
            }
            }
          />
        </div>
        <div className='address_bottom'>
          <h3>当前位置</h3>
          {
            addressList.map((item, index) => {
              return (
                <div className='address_item' key={index} onClick={() => {
                  navigate('/events',{state:item})
                }}>
                  <div className='location'>
                    <img src='https://cdn7.axureshop.com/demo2024/2293659/images/18-%E4%BD%8D%E7%BD%AE%E6%8E%88%E6%9D%83/vector_u646.svg'></img>
                    <div className='location_yuan'></div>
                  </div>
                  <div className='address_text'>
                    {item.formatted_address && (
                      <div>
                        <div>
                          <b>{item.formatted_address}</b>
                        </div>
                        <div style={{ color: '#999' }}>
                          {item.country}{item.province}{item.city}{item.district}{item.street}
                        </div>
                      </div>
                    )}
                      {!item.formatted_address && (
                      <div>
                        <div>
                          <b>{item.name}</b>
                        </div>
                        <div style={{ color: '#999' }}>
                        {item.address}
                        </div>
                      </div>
                    )}

                  </div>
                  <div>
                    <img src='https://cdn7.axureshop.com/demo2024/2293659/images/18-%E4%BD%8D%E7%BD%AE%E6%8E%88%E6%9D%83/vector_u653.svg'></img>
                  </div>
                </div>
              )
            })
          }
        </div>
      </div>
    </div>
  )
}





